<?php

namespace StudyBuddy\Controllers;

use StudyBuddy\WebPage;

/**
 * Controller to view Users' registered
 * Apps.
 * If User does not have any apps
 * then redirect to the /apiclient/ page
 * so that user may start creating new app
 *
 */
class Viewapps extends WebPage
{
	/**
	 * Pre-check to deny non-logged in user
	 * access to this page
	 *
	 * @var bool
	 */
	protected $membersOnly = true;


	/**
	 *
	 * MongoCursor with all registered apps
	 * that belong to Viewer
	 * @var object of type MongoCursor
	 */
	protected $cursor;


	/**
	 * $layoutID 1 means no side-column on page
	 *
	 * @var int
	 */
	protected $layoutID = 1;



	protected function main(){
		$this->getApps()
		->setTitle()
		->setApps();
	}


	/**
	 * Find all apps that belong the the
	 * Viewer
	 * If none are found then redirect
	 * to the page to create a new app
	 * 
	 * @throws \StudyBuddy\RedirectException
	 */
	protected function getApps(){
		$this->cursor = $this->oRegistry->Mongo->API_CLIENTS->find(array('i_uid' => $this->oRegistry->Viewer->getUid()));
		if(0 === $this->cursor->count()){
			throw new \StudyBuddy\RedirectException('/index.php?a=editapp');
		}

		return $this;
	}


	protected function setTitle(){
		$this->title = $this->aPageVars['title'] = 'Manage your applications';

		return $this;
	}


	/**
	 * Set the 'body' of the page
	 * with the content of list of user's apps
	 *
	 * @return object $this
	 */
	protected function setApps(){

		$sApps = \tplApps::loop($this->cursor);

		$this->aPageVars['body'] = \tplViewapps::parse(array('apps' =>  $sApps) );

		return $this;
	}
}
